package com.minivision.fdiot.service;

import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.minivision.fastdfs.FdfsService;
import com.minivision.fdiot.domain.StatsInfo;
import com.minivision.fdiot.entity.Stats;
import com.minivision.fdiot.repository.mysql.StatsRepository;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class StatsServiceImpl extends BaseService implements StatsService {

  @Autowired
  private StatsRepository statsRepo;

  @Autowired
  private FdfsService fdfsService;
  
  private Stats convertParam(StatsInfo param) {
    Stats record = new Stats();
    BeanUtils.copyProperties(param, record);
    record.setDetectTime(new Date(param.getTime()));
    if (StringUtils.hasText(param.getCapImg())) {
      byte[] capImgBytes = Base64.getDecoder().decode(param.getCapImg());
      try {
        record.setCapImgUrl(fdfsService.getFileUrl(fdfsService.uploadToFastDFS(param.getFaceToken() + "_cap.jpg", capImgBytes)));
      } catch (Exception e) {
        log.error("保存识别日志抓拍照片失败", e);
      }
    }
    return record;
  }

  @Override
  public Stats createStats(StatsInfo stats) {
    Stats created = statsRepo.saveAndFlush(convertParam(stats));
    return created;
  }

  @Override
  public List<Stats> createBatch(List<StatsInfo> param) {
    List<Stats> statsList = new ArrayList<>();
    for (StatsInfo createStatsParam : param) {
      statsList.add(convertParam(createStatsParam));
    }
    List<Stats> saved = statsRepo.save(statsList);
    return saved;
  }

}
